package m202405.d12;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/12 16:39
 */
public class Q24 {

    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);
        list1.next.next = new ListNode(3);
        list1.next.next.next = new ListNode(4);

        Q24 q24 = new Q24();
        q24.swapPairs(list1);
    }

    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode last = null;
        ListNode left = head;
        ListNode right = head.next;
        ListNode newHead = head;
        while (right != null) {
            ListNode temp = right.next;
            right.next = left;
            left.next = temp;
            if (last != null) {
                last.next = right;
            }
            if (newHead == head) {
                newHead = right;
            }
            last = left;
            left = left.next;
            right = left == null ? null : left.next;

        }
        return newHead;
    }
}
